<?php 
defined('RUN_KATANA') or die('Restricted access');
class Product extends Object
{
	public $MenuId;
	public $Title;
	public $Alias;
	public $SectionId;
	public $SectionTitle;
	public $CatId;
	public $CatTitle;
	public $GroupId;
	public $GroupTitle;
	public $Brand;
	public $BrandTitle;
	public $Provider;
	public $TaxId;
	public $TaxValue;
	public $FrontpageDisplay;
	
	public $Intro;
	public $Description;
	public $Details; 	
	public $Price;
	
	public $SaleStartHour;
	public $SaleEndHour;
	
	public $ProductOrder; 	
	
	/* Label Fields */
	public $StockUnit;	
	public $WeightUnit; 	
	public $DimUnit; 	
	
	/* Activation Date Fields */
	public $DateCreated;
	public $DateModified;
	public $Active;
	public $ActiveStart; 	
	public $ActiveEnd; 	
	/* Activation Date Fields End */
	
	public $Views;
	public $Variation;
	public $Variations;
	public $VariationsCount;
	public $VariationsLoaded;
	public $FirstVariationLoaded;
	public $FirstVariationId;
	public $CurrentVariationId;
	public $CurrentVariationNum;
	public $CurrentVariation;
	public $Attribute; //Single dim array with titles
	public $AttributeValues; //Single dim array with values
	public $Attributes; //2 dim array with titles and values
	public $AttributesVar; //2 dim array with titles and values and [id] for variations
	public $AttributesValuesSelected; //2 dim array with id and values of selected attributes
	public $AttributesLoaded;
	public $ProductAttributes; //ProductAttribute objects
	public $ProductAttributesLoaded;
	
	public $HasImage;
	public $ListViewImage;
	public $ImagesLoaded;
	public $Image; //Main image of the product
	public $Images; //Array with all product images
	public $ImagesByVariationId; //Array with attributeValueImages with variationId as key
	public $ImagesByAttributeValueId; //Array with attributeValueImages with attributeValueId as key
	public $ImageObject; //Main image object styla of the product
	public $ImageObjects; //All image objects styla of the product
	
	public function Product() 
	{
		self::setDataTable('product');
		self::setImagesLoaded(false);
		self::setVariationsLoaded(false);
		self::setFirstVariationLoaded(false);
		self::setProductAttributesLoaded(false);
		self::setTaxId(0);
		self::setTaxValue(0);
		self::setCurrentVariationNum(1);
		self::setTTL(CACHE_TTL);
	}
	
	/* GET FUNCTIONS */
	public function getTitle() { return self::formatText($this->Title); }
	public function getAlias() { return $this->Alias; }
	public function getSectionId() { return intval($this->SectionId); }
	public function getCatId() { return intval($this->CatId); }
	public function getGroupId() { return intval($this->GroupId); }
	public function getBrand() { return intval($this->Brand); }
	public function getProvider() { return intval($this->Provider); }
	public function getTaxId() { return intval($this->TaxId); }
	public function getSaleStartHour() { return intval($this->SaleStartHour); }
	public function getSaleEndHour() { return intval($this->SaleEndHour); }
	
	public function getTaxValue() { return $this->TaxValue; }
	public function getFrontpageDisplay() { return intval($this->FrontpageDisplay); }
	
	public function getPrice($tax = false) 
	{ 
		if(($tax == false) || ($this->TaxId == 0))
		{ return $this->Price; }
		else
		{ return number_format(round(($this->Price * $this->TaxValue),1),2,'.',''); }
	}
	
	public function getProductOrder() { return intval($this->ProductOrder); }
	public function getDateCreated() { return $this->DateCreated; }
	public function getDateModified() { return $this->DateModified; }
	public function getActive() { return intval($this->Active); }
	public function getActiveStart() { return $this->ActiveStart; }
	public function getActiveEnd() { return $this->ActiveEnd; }
	public function getViews() { return $this->Views; }
	public function getVariation($varId=0, $varNum=0) 
	{
		if($varId > 0)
		{
			self::loadVariations();
			if(isset($this->Variations[$varId]))
			{ return $this->Variations[$varId]; }
		}
		else
		{ 
			if($varNum > 0)
			{
				$vars = self::getVariations(0, $varNum);
				if(is_array($vars))
				{
					foreach($vars as $var)
					{
						if($var->getVarnum() == $varNum)
						{ 
							$this->Variation = $var;
							return $this->Variation;
						}
					}
				}
			}
			else
			{ return $this->Variation; }
		}
	}
	public function getVariations($varId=0, $varNum=0) 
	{
		self::loadVariations($varId, $varNum);
		return $this->Variations; 
	}
	public function getVariationsCount()
	{ 
		self::loadVariationsCount();
		return intval($this->VariationsCount); 
	}
	public function getVariationsLoaded() { return $this->VariationsLoaded; }
	public function getFirstVariationLoaded() { return $this->FirstVariationLoaded; }
	public function getFirstVariationId() { return intval($this->FirstVariationId); }
	public function getCurrentVariationId() { return intval($this->CurrentVariationId); }
	public function getCurrentVariationNum() { return intval($this->CurrentVariationNum); }
	public function getCurrentVariation() { return $this->CurrentVariation; }
	public function getAttribute() { return $this->Attribute; }
	public function getAttributes() { return $this->Attributes; }
	public function getAttributesVar() { return $this->AttributesVar; }
	public function getAttributeValues() { return $this->AttributeValues; }
	public function getAttributesLoaded() { return $this->AttributesLoaded; }
	public function getAttributeValue($attID=0) 
	{ 
		if($attID > 0)
		{
			if(isset($this->Attributes[$attID]['value']['value']))
			{ return $this->Attributes[$attID]['value']['value']; }
		}
	}
	public function getAttributeValueId($attID=0) 
	{ 
		if($attID > 0)
		{
			if(isset($this->Attributes[$attID]))
			{
				if(isset($this->Attributes[$attID]['value']['value_id']))
				{ return $this->Attributes[$attID]['value']['value_id']; }
			}
		}
	}
	public function getAttributeValueObject($attID=0) 
	{ 
		if($attID > 0)
		{
			if(isset($this->Attributes[$attID]['value']['value']))
			{ return $this->Attributes[$attID]['value']['value']; }
		}
	}
	public function getProductAttributes() { return $this->ProductAttributes; }
	public function getProductAttributesLoaded() { return $this->ProductAttributesLoaded; }
	
	public function getHasImage() { return intval($this->HasImage); }
	public function getListViewImage() { return $this->ListViewImage; }
	public function getImagesLoaded() { return $this->ImagesLoaded; }
	public function getImage() 
	{
		self::loadImages();
		return $this->Image; 
	}
	public function getImages() 
	{
		self::loadImages();
		return $this->Images; 
	}
	public function getImageObject() 
	{
		self::loadImages();
		return $this->ImageObject; 
	}
	public function getImageObjects() 
	{
		self::loadImages();
		return $this->ImageObjects; 
	}
	public function getImagesByVariationId() 
	{
		self::loadImages();
		return $this->ImagesByVariationId; 
	}
	public function getImagesByAttributeValueId() 
	{
		self::loadImages();
		return $this->ImagesByAttributeValueId; 
	}
	public function getLink() 
	{
		global $shop;
		global $katana;
		if(!$_GET && $shop->getSetting('FrontpageLinkPage'))
		{ return '/m/'.$this->SectionId.'/'; }
		else
		{ return '/m/'.$this->SectionId.'/?p='.$this->Id; }
	}
	
	/* SET FUNCTIONS */
	public function setTitle($val) { $this->Title=self::formatText($val); }
	public function setAlias($val) { $this->Alias=$val; }
	public function setSectionId($val) { $this->SectionId=intval($val); }
	public function setCatId($val) { $this->CatId=intval($val); }
	public function setGroupId($val) { $this->GroupId=intval($val); }
	public function setBrand($val) { $this->Brand=intval($val); }
	public function setProvider($val) { $this->Provider=intval($val); }
	public function setTaxId($val) { $this->TaxId=intval($val); }
	public function setTaxValue($val) { $this->TaxValue=$val; }
	public function setFrontpageDisplay($val) { $this->FrontpageDisplay=intval($val); }
	public function setDetails($val='') { $this->Details=self::formatHTML($val); }
	public function setPrice($val) { $this->Price=$val; }
	public function setProductOrder($val) { $this->ProductOrder=intval($val); }
	public function setDateCreated($val) { $this->DateCreated=$val; }
	public function setDateModified($val) { $this->DateModified=$val; }
	public function setActive($val) { $this->Active=intval($val); }
	public function setActiveStart($val) { $this->ActiveStart=$val; }
	public function setActiveEnd($val) { $this->ActiveEnd=$val; }
	
	public function setViews($val) { $this->Views=$val; }	
	public function setVariationsCount($val) { $this->VariationsCount=intval($val); }
	public function setVariationsLoaded($val) { $this->VariationsLoaded=$val; }	
	public function setFirstVariationLoaded($val) { $this->FirstVariationLoaded=$val; }	
	public function setFirstVariationId($val) { $this->FirstVariationId=intval($val); }
	public function setCurrentVariationId($val) { $this->CurrentVariationId=intval($val); }
	public function setCurrentVariationNum($val) { $this->CurrentVariationNum=intval($val); }
	public function setCurrentVariation($val) { $this->CurrentVariation=$val; }	
	public function setAttribute($val) { $this->Attribute=$val; }	
	public function setAttributes($val) { $this->Attributes=$val; }	
	public function setAttributesVar($val) { $this->AttributesVar=$val; }	
	public function setAttributeValues($val) { $this->AttributeValues=$val; }	
	public function setAttributesLoaded($val) { $this->AttributesLoaded=$val; }	
	public function setProductAttributes($val) { $this->ProductAttributes=$val; }	
	public function setProductAttributesLoaded($val) { $this->ProductAttributesLoaded=$val; }	
	
	public function setHasImage($val) { $this->HasImage=intval($val); }
	public function setListViewImage($val) { $this->ListViewImage=$val; }
	public function setImagesLoaded($val) { $this->ImagesLoaded=$val; }
	public function setImage($val) { $this->Image=$val; }	
	public function setImages($val) { $this->Images=$val; }	
	public function setImagesByAttributeValueId($val) { $this->ImagesByAttributeValueId=$val; }	
	
	public function update()
	{
		if(($this->Id > 0) && ($this->DataChanged == true))
		{
			global $shop;
			
			$sql  = "UPDATE ".DB_PERFIX.self::getDataTable()." SET ";
			$sql .= "`section_id`=".self::getSectionId().", ";
			$sql .= "`group_id`=".self::getGroupId().", "; 
			$sql .= "`cat_id`=".self::getCatId().", ";
			$sql .= "`brand`=".self::getBrand().", ";
			$sql .= "`provider`=".self::getProvider().", ";
			$sql .= "`FrontpageDisplay`=".self::getFrontpageDisplay().", ";
			
			if(is_numeric($this->TaxId))
			{ $sql .= '`tax_id`='.$this->TaxId.', '; }
			
			$sql .= '`SaleStartHour`='.self::getSaleStartHour().', ';
			$sql .= '`SaleEndHour`='.self::getSaleEndHour().', ';
			
			$sql .= "`title`='".self::formatText(self::getTitle())."', ";
			$sql .= "`alias`='".self::formatText(self::getAlias())."', ";
			
			if($shop->getSetting('list_view_editor') > 0)
			{
				if((self::getIntro() != '') || (self::getView() == 'commander_detail'))
				{ $sql .= "`intro`='".self::formatHTML(self::getIntro())."', ";  }
			}
			else
			{ $sql .= "`intro`='".self::formatText(self::getIntro())."', "; }
			
			if((self::getDescription() != '') || (self::getView() == 'commander_detail'))
			{ $sql .= "`Description`='".self::formatHTML(self::getDescription())."', ";  }
			
			if((self::getDetails() != '') || (self::getView() == 'commander_detail'))
			{ $sql .= '`details`=\''.self::formatHTML(self::getDetails()).'\', '; }
			
			if(is_numeric($this->HasImage))
			{ $sql .= '`has_image`='.intval($this->HasImage).', '; }
			
			if($this->Price > 0)
			{ $sql .= '`price`='.$this->Price.', ';  }
			if(($this->StockUnit != '') || (self::getView() == 'commander_detail'))
			{ $sql .= '`stock_unit`=\''.mysql_real_escape_string($this->StockUnit).'\', '; }
			if($this->WeightUnit != '')
			{ $sql .= '`weight_unit`=\''.mysql_real_escape_string($this->WeightUnit).'\', '; }
			if($this->DimUnit != '')
			{ $sql .= '`dim_unit`=\''.mysql_real_escape_string($this->DimUnit).'\', '; }
			$sql .= '`product_order`='.self::getProductOrder().', ';
			
			$start_time		= mktime(0,0,0,0,0,0);
			if($this->ActiveStart != '')
			{
				$start_time = mktime(abs(substr($this->ActiveStart, 11, 8)), 0, 0, abs(substr($this->ActiveStart, 5, 2)), abs(substr($this->ActiveStart, 8, 2)),  substr($this->ActiveStart, 0, 4));
				if($start_time > time())
				{ self::setActiveStart(date("Y-m-d H:i:s",$start_time)); }
				else
				{ self::setActiveStart('0000-00-00 00:00:00'); }
			}
			
			$end_time		= mktime(0,0,0,0,0,0);
			if($this->ActiveEnd != '')
			{
				$end_time = mktime(abs(substr($this->ActiveEnd, 11, 8)), 0, 0, abs(substr($this->ActiveEnd, 5, 2)), abs(substr($this->ActiveEnd, 8, 2)),  substr($this->ActiveEnd, 0, 4));
				
				if((!($end_time < time())) && ($start_time < $end_time))
				{ self::setActiveEnd(date("Y-m-d H:i:s",$end_time)); }
				else
				{ self::setActiveEnd('0000-00-00 00:00:00'); }
			}

			if($this->ActiveStart != '')
			{ $sql .= '`active_start`=\''.mysql_real_escape_string($this->ActiveStart).'\', '; }
			if($this->ActiveEnd != '')
			{ $sql .= '`active_end`=\''.mysql_real_escape_string($this->ActiveEnd).'\', '; }
			/*
			`views`
			*/
			$sql .= '`date_modified`=NOW(), ';
			
			$sql .= '`active`='.$this->Active.' ';
			$sql .= 'WHERE `id`='.$this->Id.';';
			
			//echo $sql;
			$result = mysql_query($sql);
		}
	}
	
	public function loadAttributes()
	{
		if(($this->Id > 0) && ($this->AttributesLoaded == false))
		{
			global $db;
			$sql  = ' SELECT attr.*, pval.id AS pvalid, pval.value_id, pval.value';
			$sql .= ' FROM '.DB_PERFIX.'product_attributes AS attr ';
			$sql .= ' LEFT JOIN '.DB_PERFIX.'product_to_attributes AS pta ON pta.attribute_id=attr.id ';
			$sql .= ' LEFT JOIN '.DB_PERFIX.'product_vals AS pval ON pval.product_id='.self::getId().' AND pval.attribute_id=attr.id ';
			$sql .= ' WHERE pta.product_id='.self::getId().' ORDER BY pta.id ASC;';
			// AND attr.active=1
			$data = $db->fetch($sql, CACHE_TTL);
			if(is_array($data))
			{
				$i=0;
				foreach($data as $row)
				{
					$this->Attributes[$row['id']]['id'] = $row['id'];
					$this->Attributes[$row['id']]['type'] = $row['type'];
					$this->Attributes[$row['id']]['title'] = $row['title'];
					$this->Attributes[$row['id']]['title_import'] = $row['title_import'];
					$this->Attributes[$row['id']]['effect'] = $row['effect'];
					$this->Attributes[$row['id']]['effect_image'] = $row['effect_image'];
					$this->Attributes[$row['id']]['predefined'] = $row['predefined'];
					$this->Attributes[$row['id']]['display'] = $row['display'];
					$this->Attributes[$row['id']]['display_list'] = $row['display_list'];
					$this->Attributes[$row['id']]['display_all'] = $row['display_all'];
					$this->Attributes[$row['id']]['val_types'] = $row['val_types'];
					$this->Attributes[$row['id']]['active'] = $row['active'];
					if($row['effect'] == 0)
					{
						$this->Attributes[$row['id']]['value']['id'] = $row['pvalid'];
						$this->Attributes[$row['id']]['value']['product_id'] = $this->Id;
						$this->Attributes[$row['id']]['value']['attribute_id'] = $row['id'];
						$this->Attributes[$row['id']]['value']['value_id'] = $row['value_id'];
						$this->Attributes[$row['id']]['value']['value'] = $row['value'];
					}
					if($row['effect'] == 1)
					{ $this->AttributesVar[$row['id']] = $this->Attributes[$row['id']]; }
					
					if($_POST['a_'.$row['id'].'_v'] > 0)
					{ $this->AttributesValuesSelected[$row['id']] = $_POST['a_'.$row['id'].'_v']; }
					
					$i++;
				}
			}
			unset($data);
			self::setAttributesLoaded(true);
		}
	}
	
	public function getVariationIdByCombination($combArray)
	{
		$varCombID = 0;
		if(count($combArray) > 0)
		{
			//echo '<br />$combArray:';
			//print_r($combArray);
			
			foreach($combArray as $valId)
			{ 
				$varIdIn = '';
				if(count($possibleVariations) > 0)
				{
					$IdIn = '';
					foreach($possibleVariations as $varId)
					{
						if($IdIn == '')
						{ $IdIn = ''.$varId; }
						else
						{ $IdIn .= ', '.$varId; }
					}
					$varIdIn = ' AND (variation_id IN ('.$IdIn.'))';
				}
				$sql  = ' SELECT variation_id FROM '.DB_PERFIX.'product_var_vals WHERE product_id='.$this->Id.' AND value_id ='.$valId.$varIdIn.';';
				//echo '<br />'.$sql;
				$result = mysql_query($sql);
				unset($possibleVariations);
				if(mysql_num_rows($result) > 0)
				{
					while($row = mysql_fetch_array($result))
					{ 
						$possibleVariations[$row['variation_id']] = $row['variation_id']; 
						//self::setCurrentVariationId($row['variation_id']);
						if(mysql_num_rows($result) < 2)
						{ $varCombID = $row['variation_id']; }
					}
				}
			}
		}
		return $varCombID;
	}
	
	public function getVarValsByCombination($combArray)
	{
		$varCombID = 0;
		if(count($combArray) > 0)
		{
			//echo '<br />$combArray:';
			//print_r($combArray);
			
			foreach($combArray as $valId)
			{ 
				$varIdIn = '';
				if(count($possibleVariations) > 0)
				{
					$IdIn = '';
					foreach($possibleVariations as $varId)
					{
						if($IdIn == '')
						{ $IdIn = ''.$varId; }
						else
						{ $IdIn .= ', '.$varId; }
					}
					$varIdIn = ' AND (variation_id IN ('.$IdIn.'))';
				}
				$sql  = ' SELECT variation_id, attribute_id, value_id FROM '.DB_PERFIX.'product_var_vals WHERE product_id='.$this->Id.' AND value_id ='.$valId.$varIdIn.';';
				//echo '<br />'.$sql;
				
				unset($possibleVariations);
				unset($variationsIdArray);
				
				$result = mysql_query($sql);
				if(mysql_num_rows($result) > 0)
				{
					unset($variationsIdArray);
					$rows = mysql_num_rows($result);
					while($row = mysql_fetch_array($result))
					{ 
						$possibleVariations[$row['variation_id']] = $row['variation_id']; 
						//self::setCurrentVariationId($row['variation_id']);
						if(mysql_num_rows($result) < 2)
						{ $varCombID = $row['variation_id']; }
						else
						{ 
							$variationsIdArray[$i]['variation_id'] = $row['variation_id']; 
							$variationsIdArray[$i]['attribute_id'] = $row['attribute_id'];
							$variationsIdArray[$i]['value_id'] 	   = $row['value_id']; 
						}
						$i++;
					}
				}
			}
		}
		if($varCombID > 0)
		{ return $varCombID; }
		else
		{ return $variationsIdArray; }
	}
	
	public function getPossibleAttributeValues($attId=0)
	{
		if($attId > 0)
		{
			self::loadVariations();
			if(isset($this->AttributesVar[$attId]))
			{
				foreach(array_keys($this->Variations) as $varnum)
				{
					
				}
			}
		}
	}
	
	
	public function getVariationByAttributeValueId($attId=0, $valId=0)
	{
		if(($attId > 0) && ($valId > 0))
		{
			self::loadVariations();
			$vnum = 0;
			if(isset($this->AttributesVar[$attId]))
			{
				foreach(array_keys($this->Variations) as $varnum)
				{
					if($this->Variations[$varnum]->getAttributeValueId($attId) == $valId)
					{ 
						$vnum = $varnum; 
						break;
					}
				}
				if($vnum > 0)
				{ return $this->Variations[$vnum]; }
			}
			
		}
	}
	
	public function loadImages()
	{
		if((self::getId() > 0) && (self::getItemLoaded('Images') == false))
		{
			$sql = 'SELECT * FROM '.DB_PERFIX.'shop_images WHERE product_id='.self::getId().' ORDER BY `default` DESC;';
			$result = mysql_query($sql);
			if(mysql_num_rows($result) > 0)
			{
				$i=0;
				while($row = mysql_fetch_array($result))
				{
					foreach(array_keys($row) as $key)
					{ $this->Images[$row['id']][$key] = $row[$key]; }
					
					$this->ImageObjects[$row['id']] = new Image();
					$this->ImageObjects[$row['id']]->setId($row['id']);
					$this->ImageObjects[$row['id']]->setDataTable('shop_images');
					$this->ImageObjects[$row['id']]->setParentIdField('product_id');
					$this->ImageObjects[$row['id']]->setParentId(self::getId());
					$this->ImageObjects[$row['id']]->setFolderPath(PRODUCT_PATH);
					$this->ImageObjects[$row['id']]->setFolderUrl(PRODUCT_URL);
					$this->ImageObjects[$row['id']]->setFilename($row['image']);
					
					$this->ImageObjects[$row['id']]->setProductId($row['product_id']);
					$this->ImageObjects[$row['id']]->setVariationId($row['variation_id']);
					$this->ImageObjects[$row['id']]->setVariationValueId($row['variation_value_id']);
					$this->ImageObjects[$row['id']]->setDefault($row['default']);
					
					$this->Images[$row['id']]['URL'] = PRODUCT_URL.$item[$i]['image'];
					if($row['default'] > 0)
					{ 
						$this->Image = $this->Images[$row['id']]; 
						$this->ImageObject = $this->ImageObjects[$row['id']]; 
					}
					if($row['variation_value_id'] > 0)
					{ $this->ImagesByAttributeValueId[$row['variation_value_id']] = $this->Images[$row['id']]; }
					if($row['variation_id'] > 0)
					{ $this->ImagesByVariationId[$row['variation_id']] = $this->Images[$row['id']]; }
					$i++;
				}
			}
			unset($result);
			if(count($this->Images) > 0)
			{ self::setHasImage(1); }
			else
			{ self::setHasImage(0); }
			self::setImagesLoaded(true);
			self::setItemLoaded('Images', true);
		}
	}
	
	public function addVariation($title='', $ident = '', $live=1)
	{
		if($live == 1)
		{ self::loadVariations(); }
		if((self::getId() > 0) && ($title != ''))
		{
			
			$varnum = 1;
			$result = mysql_query('SELECT varnum FROM '.DB_PERFIX.'product_vars WHERE product_id='.self::getId().' ORDER BY varnum DESC LIMIT 1;');
			if($result)
			{
				while($row = mysql_fetch_array($result))
				{ 
					$varnum = intval($row['varnum']);
					$varnum++;
				}
			}
			unset($result);
			
			if($ident == '')
			{ $ident = self::getSectionId().'-'.self::getId().'-'.$varnum; }
			else
			{ $ident = trim($ident); }
			
			$sql =  'INSERT INTO '.DB_PERFIX.'product_vars (';
			$sql .= '`product_id`, ';
			$sql .= '`varnum`, ';
			$sql .= '`var_title`, ';
			$sql .= '`identity`, ';
			$sql .= '`buy_min`, ';
			$sql .= '`std_price`, ';
			$sql .= '`net_weight`, ';
			$sql .= '`gros_weight`, ';
			$sql .= '`length`, ';
			$sql .= '`width`, ';
			$sql .= '`height` ';
			$sql .= ') ';
			$sql .= ' VALUES (';
			$sql .= self::getId().', ';
			$sql .= intval($varnum).', ';
			$sql .= '"'.$title.'", ';
			$sql .= '"'.$ident.'", ';
			$sql .= $this->Variations[self::getFirstVariationId()]->getBuyMin().', ';
			$sql .= $this->Variations[self::getFirstVariationId()]->getStdPrice().', ';
			$sql .= $this->Variations[self::getFirstVariationId()]->getNetWeight().', ';
			$sql .= $this->Variations[self::getFirstVariationId()]->getGrosWeight().', ';
			$sql .= $this->Variations[self::getFirstVariationId()]->getLength().', ';
			$sql .= $this->Variations[self::getFirstVariationId()]->getWidth().', ';
			$sql .= $this->Variations[self::getFirstVariationId()]->getHeight().'';
			$sql .= ');';
			
			mysql_query($sql);
			
			$result = mysql_query('SELECT id FROM '.DB_PERFIX.'product_vars WHERE product_id='.self::getId().' AND varnum='.intval($varnum).' ORDER BY id DESC LIMIT 1;');
			if($result)
			{
				while($row = mysql_fetch_array($result))
				{ $id = $row['id']; }
			}
			unset($result);
			//echo $sql;
			if($id > 0)
			{
				self::setVariationsLoaded(false);
				self::setFirstVariationLoaded(false);
				if($live == 1)
				{ self::loadVariations(); }
				else
				{ self::loadVariations($id); }
				return ($id);
			}
		}
	}
	
	public function loadVariationsCount()
	{
		if(!self::getItemLoaded('VariationsCount'))
		{
			global $db;
			$sql  = 'SELECT COUNT(pv.id) AS VariationsCount ';
			$sql .= 'FROM '.DB_PERFIX.'product_vars AS pv WHERE pv.product_id='.self::getId();
			$sql .= ';';
			
			$result = $db->query($sql);
			$data = $db->fetch($sql, self::getTTL());
			
			if(is_array($data))
			{
				foreach($data as $row)
				{ 
					if($row['VariationsCount'] > 0)
					{ self::setVariationsCount(intval($row['VariationsCount'])); }
				}
				
			}
			unset($data);
			self::setItemLoaded('VariationsCount', true);
		}
	}
	
	public function loadVariations($id=0, $varnum=0) 
	{
		//echo 'Load Variations<br>';
		if(($this->Id > 0) && (self::getVariationsLoaded() == false))
		{
			global $shop;
			global $db;
			
			//unset($this->Variations);
			//print_r($shop);
			//echo '<br />loadVariations<br />MemmoryUsage:'.memory_get_usage();
			self::loadAttributes();
			//echo '<br />loadAttributes<br />MemmoryUsageNow:'.memory_get_usage();
			if(count($this->AttributesValuesSelected) > 0)
			{
				//echo '<br />$this->AttributesValuesSelected:';
				//print_r($this->AttributesValuesSelected);
				foreach($this->AttributesValuesSelected as $valId)
				{ 
					$varIdIn = '';
					if(count($possibleVariations) > 0)
					{
						$IdIn = '';
						foreach($possibleVariations as $varId)
						{
							if($IdIn == '')
							{ $IdIn = ''.$varId; }
							else
							{ $IdIn .= ', '.$varId; }
						}
						//$varIdIn = ' AND (pvl.variation_id IN ('.$IdIn.'))';
						$varIdIn = ' AND (variation_id IN ('.$IdIn.'))';
					}
					/*
					$sql  = 'SELECT pvl.variation_id ';
					$sql .= 'FROM '.DB_PERFIX.'product_var_vals AS pvl ';
					$sql .= 'LEFT JOIN '.DB_PERFIX.'product_attributes AS pat ON (pat.id=pvl.attribute_id) ';
					$sql .= 'WHERE pat.active=1 AND pvl.product_id='.self::getId().' AND pvl.value_id ='.$valId.$varIdIn.';';
					*/
					$sql  = ' SELECT variation_id FROM '.DB_PERFIX.'product_var_vals WHERE product_id='.self::getId().' AND value_id ='.$valId.$varIdIn.';';
					$data = $db->fetch($sql, CACHE_TTL);
					//echo $sql;
					// ##
					
					if(is_array($data))
					{
						unset($possibleVariations);
						foreach($data as $row)
						{
							$possibleVariations[$row['variation_id']] = $row['variation_id'];
							if(count($data) < 2)
							{ self::setCurrentVariationId($row['variation_id']); }
						}
					}
				}
			}
			
			$loadVarVals = false;
			
			$sql  = 'SELECT ';
			$sql .= 'pv.id, ';
			$sql .= 'pv.product_id, ';
			$sql .= 'pv.varnum, ';
			
			$sql .= 'pv.identity, ';
			$sql .= 'pv.ext_identity, ';
			if($shop->GlobalSettings['buy_min'])
			{ $sql .= 'pv.buy_min, '; }
			
			if($shop->GlobalSettings['stock'])
			{
				$sql .= 'pv.stock_count, ';
				$sql .= 'pv.stock_add_date, ';
				$sql .= 'pv.stock_add_quan, ';
				$sql .= 'pv.stock_add_txt, ';
			}
			if($shop->GlobalSettings['shipping_weight_volume_active'])
			{
				$sql .= 'pv.net_weight, ';
				$sql .= 'pv.gros_weight, ';
				$sql .= 'pv.length, ';
				$sql .= 'pv.width, ';
				$sql .= 'pv.height, ';
			}
			$sql .= 'pv.std_price, ';
			if($shop->GlobalSettings['now_price'])
			{ 
				$sql .= 'pv.now_price, '; 
				$sql .= 'pv.NowPriceDateEnd, ';
			}
			if($shop->GlobalSettings['offer_price'])
			{
				$sql .= 'pv.offer_price, ';
				$sql .= 'pv.offer_start, ';
				$sql .= 'pv.offer_end, ';
			}
			$sql .= 'pv.var_title, ';
			$sql .= 'pv.active ';
			
			$sql .= ' FROM '.DB_PERFIX.'product_vars AS pv WHERE pv.product_id='.$this->Id;
			
			if(self::getFirstVariationLoaded() == true)
			{ $sql .= ' AND pv.varnum > 1 '; }
			
			if(intval($id) > 0)
			{ $sql .= ' AND pv.id='.intval($id).' ';}
			
			if(intval($varnum) > 1)
			{ $sql .= ' AND pv.varnum='.intval($varnum);}
			
			$sql .= ' ORDER BY pv.varnum ASC;';
			
			$data = $db->fetch($sql, 0);
			if(is_array($data))
			{
				if(self::getFirstVariationLoaded() == true)
				{ $i = 2; }
				else
				{ 
					unset($this->Variations);
					$i = 1;
				}
				
				foreach($data as $row)
				{
					if($i == 1)
					{ self::setFirstVariationId($row['id']); }
					
					$this->Variations[$row['id']] = new ProductVariation;
					$this->Variations[$row['id']]->setId($row['id']);
					$this->Variations[$row['id']]->setProductId($row['product_id']);
					$this->Variations[$row['id']]->setVarnum($row['varnum']);
					$this->Variations[$row['id']]->setVarTitle($row['var_title']);
					$this->Variations[$row['id']]->setActive($row['active']);
					$this->Variations[$row['id']]->setIdentity($row['identity']);
					if($row['ext_identity'] == '')
					{ $this->Variations[$row['id']]->setExtIdentity($row['identity']); }
					else
					{ $this->Variations[$row['id']]->setExtIdentity($row['ext_identity']); }
					
					if($shop->GlobalSettings['buy_min'])
					{ $this->Variations[$row['id']]->setBuyMin($row['buy_min']); }
					
					if($shop->GlobalSettings['stock'])
					{
						$this->Variations[$row['id']]->setStockCount($row['stock_count']);
						$this->Variations[$row['id']]->setStockAddDate($row['stock_add_date']);
						$this->Variations[$row['id']]->setStockAddQuan($row['stock_add_quan']);
						$this->Variations[$row['id']]->setStockAddTxt($row['stock_add_txt']);
					}
					
					if($shop->GlobalSettings['shipping_weight_volume_active'])
					{
						$this->Variations[$row['id']]->setNetWeight($row['net_weight']);
						$this->Variations[$row['id']]->setGrosWeight($row['gros_weight']);
						$this->Variations[$row['id']]->setLength($row['length']);
						$this->Variations[$row['id']]->setWidth($row['width']);
						$this->Variations[$row['id']]->setHeight($row['height']);
					}
					
					if($row['std_price'] > 0)
					{ $this->Variations[$row['id']]->setStdPrice($row['std_price']); }
					else
					{ $this->Variations[$row['id']]->setStdPrice($this->Price); }
					
					if($shop->GlobalSettings['now_price'])
					{ 
						$this->Variations[$row['id']]->setNowPrice($row['now_price']);
						$this->Variations[$row['id']]->setNowPriceDateEnd($row['NowPriceDateEnd']);
					}
					if($shop->GlobalSettings['offer_price'])
					{
						$this->Variations[$row['id']]->setOfferPrice($row['offer_price']);
						$this->Variations[$row['id']]->setOfferStart($row['offer_start']);
						$this->Variations[$row['id']]->setOfferEnd($row['offer_end']);
					}
					$this->Variations[$row['id']]->setTaxId($this->TaxId);
					$this->Variations[$row['id']]->setTaxValue($this->TaxValue);
					//echo 'loading:';
					//print_r($this->AttributesVar);
					if(count($this->AttributesVar) > 0)
					{ $this->Variations[$row['id']]->setAttributes($this->AttributesVar); }
					
					if(intval($_REQUEST['variation']) == $row['id'])
					{ self::setCurrentVariationId($row['id']); }
					
					if(self::getCurrentVariationId() == $row['id'])
					{ self::setCurrentVariationNum($row['id']); }
					//echo '<br />VariationLoaded:'.$row['id'].' ('.count($this->Variations).'):'.memory_get_usage();
					
					$i++;
				}
			}
			if((count($this->Variations) > 0) && (count($this->AttributesVar) > 0))
			{
				/* Load attribut values that has effect on variations */
				
				$sql  = ' SELECT * FROM '.DB_PERFIX.'product_var_vals WHERE product_id='.$this->Id;
				
				if (!defined('RUN_COMMANDER'))
				{
					$where = '';
					foreach($this->AttributesVar as $av)
					{
						if($av['display_all'] == 0)
						{
							if($where != '')
							{ $where .= ' OR attribute_id='.$av['id']; }
							else
							{ $where .= 'attribute_id='.$av['id']; }
						}
					}
	
					if($where != '')
					{ 
						$where = '('.$where.')'; 
						if(self::getCurrentVariationId() > 0)
						{ $sql  .= ' AND (variation_id='.self::getCurrentVariationId().' OR '.$where.')'; }
					}
					else
					{
						if(self::getCurrentVariationId() > 0)
						{ $sql  .= ' AND (variation_id='.self::getCurrentVariationId().')'; }
					}
				}
				$data = $db->fetch($sql, 0);
				if(is_array($data))
				{
					foreach($data as $row)
					{
						if(is_object($this->Variations[$row['variation_id']]))
						{
							$this->Variations[$row['variation_id']]->Attributes[$row['attribute_id']]['value']['id'] = $row['id'];
							$this->Variations[$row['variation_id']]->Attributes[$row['attribute_id']]['value']['product_id'] = $row['product_id'];
							$this->Variations[$row['variation_id']]->Attributes[$row['attribute_id']]['value']['variation_id'] = $row['variation_id'];
							$this->Variations[$row['variation_id']]->Attributes[$row['attribute_id']]['value']['attribute_id'] = $row['attribute_id'];
							$this->Variations[$row['variation_id']]->Attributes[$row['attribute_id']]['value']['value_id'] = $row['value_id'];
							$this->Variations[$row['variation_id']]->Attributes[$row['attribute_id']]['value']['value'] = $row['value'];
						}
					}
				}
			}
			//self::saveToCache($this->Variations);
	
			self::setVariationsLoaded(true);
			self::setFirstVariationLoaded(true);
		}
	}
	
	public function deleteVariation($id = 0)
	{
		if(($this->Id > 0) && ($id > 0))
		{
			$delete = 'DELETE FROM '.DB_PERFIX.'product_var_vals WHERE product_id='.$this->Id.' AND variation_id='.$id.';';
			$result = mysql_query($delete);
			$delete = 'DELETE FROM '.DB_PERFIX.'product_vars WHERE product_id='.$this->Id.' AND id='.$id.';'; 
			$result = mysql_query($delete);
			unset($this->Variations[$id]);
			
			$sql  = ' SELECT id FROM '.DB_PERFIX.'product_vars WHERE product_id='.$this->Id.' ORDER BY varnum ASC;';
			$result = mysql_query($sql); 
			if(mysql_num_rows($result) > 0)
			{
				$i=1;
				while($row = mysql_fetch_array($result))
				{
					$update  = 'UPDATE '.DB_PERFIX.'product_vars SET `varnum`='.$i.' WHERE id='.$row['id'].'; ';
					mysql_query($update); 
					$i++;
				}
			}
			unset($result);
			
			self::setVariationsLoaded(false);
			self::loadVariations();
			return true;
		}
	}
}
?>